﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zhaoxi.DesignPattern.FlyweightPattern.Abstracts;
using Zhaoxi.DesignPattern.FlyweightPattern.Services;

namespace Zhaoxi.DesignPattern.FlyweightPattern
{
    /// <summary>
    /// 享元工厂：
    /// 1  完成对象的创建，包一层
    /// 2  完成对象的复用
    /// </summary>
    public class FlyweightFactory
    {
        private static Dictionary<WordType, AbstractWord> FlyweightFactory_Dictionary = new Dictionary<WordType, AbstractWord>();
        private static object FlyweightFactory_Lock = new object();

        public static AbstractWord CreateWord(WordType wordType)
        {
            //双检锁：if-lock-if，最外层的判断，是为了初始化之后的线程避免等待---之前讲单例模式很细致
            if (!FlyweightFactory_Dictionary.ContainsKey(wordType))
            {
                lock (FlyweightFactory_Lock)
                {
                    if (!FlyweightFactory_Dictionary.ContainsKey(wordType))
                    {
                        AbstractWord word = null;
                        switch (wordType)
                        {
                            case WordType.E:
                                word = new EWord();
                                break;
                            case WordType.L:
                                word = new LWord();
                                break;
                            case WordType.V:
                                word = new VWord();
                                break;
                            case WordType.N:
                                word = new NWord();
                                break;
                            default:
                                throw new Exception("wrong wordType");
                        }
                        FlyweightFactory_Dictionary[wordType] = word;
                    }
                }
            }
            
            return FlyweightFactory_Dictionary[wordType];
        }

        public enum WordType
        {
            E,
            L,
            V,
            N
        }
    }
}
